package reduce.fz.com.reduce.adapter;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.support.v4.view.PagerAdapter;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

import reduce.fz.com.reduce.R;
import reduce.fz.com.reduce.bean.Pic;
import reduce.fz.com.reduce.bean.WitnessCard;
import reduce.fz.com.reduce.constant.ParamConst;
import reduce.fz.com.reduce.custom.JazzyViewPager;
import reduce.fz.com.reduce.custom.NetworkImageView;
import reduce.fz.com.reduce.custom.OutlineContainer;
import reduce.fz.com.reduce.util.DateUtil;
import reduce.fz.com.reduce.util.HttpUtils;
import reduce.fz.com.reduce.util.ImageDisplay;
import reduce.fz.com.reduce.util.ScreenUtils;
import reduce.fz.com.reduce.util.VideoPlayerUtils;
import reduce.fz.com.reduce.util.VideoPlayerUtils.PlayState;

import static reduce.fz.com.reduce.util.VideoPlayerUtils.PlayState.START;

/**
 * Created by qingshengzheng on 15/9/27.
 */
public class WitnessCardAdapter extends PagerAdapter {
    private LayoutInflater layoutInflater;
    public List<WitnessCard> userWitness;
    private WitnessCardListener cardListener;
    private Context context;
    private JazzyViewPager viewPager;
    private Activity mActivity;
    //图片区域间距
    private int stubMagin = 0;
    //根据屏幕计算图片区域宽度
    private int stubWidth = 0;
    //根据屏幕计算图片区域高度=0;
    private int stubHeight = 0;
    //图片之间边距
    private int margin = 0;
    //图片之间下边距
    private int padding = 0;

    public void addCard(List<WitnessCard> cards) {
        if (userWitness != null) {
            userWitness.addAll(cards);
            notifyDataSetChanged();
        }
    }

    /**
     * 构造参数 用户见证列表，内部操作监听
     *
     * @param witness
     * @param listener
     */
    public WitnessCardAdapter(Activity activity, List<WitnessCard> witness, WitnessCardListener listener, JazzyViewPager viewPager) {
        this.context = activity.getBaseContext();
        this.mActivity = activity;
        this.viewPager = viewPager;
        this.layoutInflater = LayoutInflater.from(context);
        this.userWitness = witness;
        this.cardListener = listener;
        this.stubMagin = context.getResources().getDimensionPixelSize(R.dimen.witness_card_main_margin);
        //白色卡片内部区域宽度
        this.margin = context.getResources().getDimensionPixelSize(R.dimen.witness_card_pic_margin);
        this.padding = context.getResources().getDimensionPixelSize(R.dimen.witness_card_content_padding);
        this.stubWidth = ScreenUtils.getScreenW() - 2 * stubMagin - 2 * padding;
        this.stubHeight = ScreenUtils.getScreenH() - getByResourceId(R.dimen.dimen_210) - 2 * getByResourceId(R.dimen.witness_card_main_margin) - 2 * getByResourceId(R.dimen.witness_card_content_padding) - getByResourceId(R.dimen.witness_card_header_height) - getByResourceId(R.dimen.witness_card_desc_margin) - getByResourceId(R.dimen.witness_card_desc_height) - getByResourceId(R.dimen.witness_card_bottom_margin) - getByResourceId(R.dimen.witness_card_bottom_height);
        notifyDataSetChanged();
    }

    public int getByResourceId(int id) {
        return context.getResources().getDimensionPixelSize(id);
    }


    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView(viewPager.findViewFromObject(position));
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        // super.instantiateItem(container, position);
       /* TextView text = new TextView(context);
        text.setGravity(Gravity.CENTER);
        text.setTextSize(30);
        text.setTextColor(Color.BLACK);
        text.setText("Page " + position);
        text.setPadding(30, 30, 30, 30);
        int bg = Color.rgb((int) Math.floor(Math.random()*128)+64,
                (int) Math.floor(Math.random()*128)+64,
                (int) Math.floor(Math.random()*128)+64);
        text.setBackgroundColor(bg);
        container.addView(text, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        viewPager.setObjectForPosition(text, position);
        return text;
*/
        View view = layoutInflater.inflate(R.layout.view_witness_card, null);
        container.addView(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        MyViewHolder viewHold = new MyViewHolder(view, cardListener);
        viewHold.renderView(userWitness.get(position));
        viewPager.setObjectForPosition(view, position);
        return view;
    }

    @Override
    public int getCount() {
        return userWitness.size();
    }

    @Override
    public boolean isViewFromObject(View view, Object obj) {
        if (view instanceof OutlineContainer) {
            return ((OutlineContainer) view).getChildAt(0) == obj;
        } else {
            return view == obj;
        }
    }


    public class MyViewHolder implements View.OnClickListener {
        private NetworkImageView mIvUserHeader;
        private TextView mTvNickName;
        private TextView mTvPubTime;
        private ViewStub picStub;
        private NetworkImageView mIvPic1;
        private NetworkImageView mIvPic2;
        private NetworkImageView mIvPic3;
        private NetworkImageView mIvPic4;
        private NetworkImageView mIvPic5;
        private NetworkImageView mIvPic6;
        private TextView mTvWitnessDesc;
        private TextView mWitnessNo;
        private TextView mWitnessYes;
        private TextView mWitnessComments;
        private View view;
        private WitnessCard witnessCard;
        private WitnessCardListener cardListener;
        private RelativeLayout mRlWitnessNo;
        private RelativeLayout mRlWitnessComments;
        private ArrayList<String> imageList;
        private SurfaceView videoSurface;
        private ImageView ivPlay;
        private VideoPlayerUtils playUitls;

        public List<String> initImageLit() {
            List<String> imageLit = new ArrayList<String>();
            if (witnessCard.affimages == null || witnessCard.affimages.size() == 0)
                return null;
            List<Pic> pics = witnessCard.affimages;
            for (int i = 0; i < pics.size(); i++) {
                imageLit.add(pics.get(i).url);
            }
            return imageLit;
        }


        public MyViewHolder(View itemView, WitnessCardListener cardListener) {
            this.view = itemView;
            this.cardListener = cardListener;
            initWidget(itemView);

        }


        public void initWidget(View view) {
            this.view = view;

            mIvUserHeader = (NetworkImageView) view.findViewById(R.id.iv_user_header);
            mTvNickName = (TextView) view.findViewById(R.id.tv_user_nickname);
            mTvPubTime = (TextView) view.findViewById(R.id.tv_pub_time);
            mTvWitnessDesc = (TextView) view.findViewById(R.id.tv_witness_desc);
            mWitnessNo = (TextView) view.findViewById(R.id.tv_witness_no);
            mWitnessYes = (TextView) view.findViewById(R.id.tv_witness_yes);
            mWitnessComments = (TextView) view.findViewById(R.id.tv_witness_comments);
            mRlWitnessNo = (RelativeLayout) view.findViewById(R.id.ll_witness_no);
            mRlWitnessComments = (RelativeLayout) view.findViewById(R.id.ll_witness_comments);

        }

        public void renderView(WitnessCard card) {
            this.witnessCard = card;
            this.imageList = (ArrayList<String>) initImageLit();
            if (card.user != null) {
                mIvUserHeader.setImageUrl(card.user.avatar, HttpUtils.getAvatarImageLoader());
                mTvNickName.setText(card.user.nickname);
            }
            mTvPubTime.setText(DateUtil.getInterval(card.pubtime));
            mTvWitnessDesc.setText(card.description);
            mWitnessYes.setOnClickListener(this);
            mWitnessNo.setOnClickListener(this);
            if (card.witnessAttach.haswitness) {
                mWitnessYes.setEnabled(false);
                mWitnessNo.setEnabled(false);
            } else {
                mWitnessYes.setEnabled(true);
                mWitnessNo.setEnabled(true);
            }
            if (card.witnessAttach.reply_count == 0) {
                mWitnessComments.setText("评论");
            } else {
                mWitnessComments.setText("评论" + card.witnessAttach.reply_count + "+");
            }
            mWitnessComments.setOnClickListener(this);
            if (witnessCard.cardtype == ParamConst.CARD_TYPE_VIDEO) {
                initVideoStub(card);
                renderVideo(card);

            } else {
                initPicStub(card);
                renderPic(card);
            }
            setWitnessState(card.getWitnessAttach().haswitness, 0);
        }

        public void renderVideo(WitnessCard card) {
            ivPlay.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    play();
                    ivPlay.setVisibility(View.GONE);
                }
            });


        }

        //播放视频
        public void play() {
            playUitls.playUrl(witnessCard.video.url);
        }


        public void renderPic(WitnessCard card) {


            //初始化图片尺寸
            initPicSize();
            List<Pic> pics = card.affimages;
            if (pics.size() >= 1) {
                mIvPic1.setImageUrl(pics.get(0).url, HttpUtils.getImageLoader());
                mIvPic1.setOnClickListener(this);
            }
            if (pics.size() >= 2) {
                mIvPic2.setImageUrl(pics.get(1).url, HttpUtils.getImageLoader());
                mIvPic2.setOnClickListener(this);
            }
            if (pics.size() >= 3) {
                mIvPic3.setImageUrl(pics.get(2).url, HttpUtils.getImageLoader());
                mIvPic3.setOnClickListener(this);
            }
            if (pics.size() >= 4) {
                mIvPic4.setImageUrl(pics.get(3).url, HttpUtils.getImageLoader());
                mIvPic4.setOnClickListener(this);
            }
            if (pics.size() >= 5) {
                mIvPic5.setImageUrl(pics.get(4).url, HttpUtils.getImageLoader());
                mIvPic5.setOnClickListener(this);
            }
            if (pics.size() >= 6) {
                mIvPic6.setImageUrl(pics.get(5).url, HttpUtils.getImageLoader());
                mIvPic6.setOnClickListener(this);
            }

        }

        /**
         * 有一张图片时
         */
        public void has1Pic() {
            int width = stubWidth;
            int height = stubWidth;
            LinearLayout.LayoutParams params = getLayoutParams(width, height, 0, 0, 0, 0);
            mIvPic1.setLayoutParams(params);
        }

        public LinearLayout.LayoutParams getLayoutParams(int width, int height, int marginLeft, int marginTop, int marginRight, int marginBottom) {
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(width, height);
            params.setMargins(marginLeft, marginTop, marginRight, marginBottom);
            return params;
        }

        /**
         * 有2张图片时
         */
        public void has2Pic() {
            int width = stubWidth;
            int height = (stubWidth - margin) / 2;
            mIvPic1.setLayoutParams(getLayoutParams(width, height, 0, 0, 0, 0));
            mIvPic2.setLayoutParams(getLayoutParams(width, height, 0, margin, 0, 0));
        }

        /**
         * 有三张图片时
         */
        public void has3Pic() {
            int width = stubWidth;
            int height = (stubWidth - margin) / 2;
            mIvPic1.setLayoutParams(getLayoutParams(width, height, 0, 0, 0, 0));
            mIvPic2.setLayoutParams(getLayoutParams(height, height, 0, margin, 0, 0));
            mIvPic3.setLayoutParams(getLayoutParams(height, height, margin, margin, 0, 0));

        }

        /**
         * 有4张图片时
         */
        public void has4Pic() {
            int width = (stubWidth - margin) / 2;
            mIvPic1.setLayoutParams(getLayoutParams(width, width, 0, 0, 0, 0));
            mIvPic2.setLayoutParams(getLayoutParams(width, width, margin, 0, 0, 0));
            mIvPic3.setLayoutParams(getLayoutParams(width, width, 0, margin, 0, 0));
            mIvPic4.setLayoutParams(getLayoutParams(width, width, margin, margin, 0, 0));

        }

        /**
         * 有5张图片时
         */
        public void has5Pic() {
            int width = (stubHeight - 2 * margin) / 3;
            mIvPic1.setLayoutParams(getLayoutParams(width * 2, width, 0, 0, 0, 0));
            mIvPic2.setLayoutParams(getLayoutParams(width, width, 0, margin, 0, 0));
            mIvPic3.setLayoutParams(getLayoutParams(width, width, margin, margin, 0, 0));
            mIvPic4.setLayoutParams(getLayoutParams(width, width, 0, margin, 0, 0));
            mIvPic5.setLayoutParams(getLayoutParams(width, width, margin, margin, 0, 0));
        }

        /**
         * 有6张图片时
         */
        public void has6Pic() {
            int width = (stubHeight - 2 * margin) / 3;
            mIvPic1.setLayoutParams(getLayoutParams(width, width, 0, 0, 0, 0));
            mIvPic2.setLayoutParams(getLayoutParams(width, width, margin, 0, 0, 0));
            mIvPic3.setLayoutParams(getLayoutParams(width, width, 0, margin, 0, 0));
            mIvPic4.setLayoutParams(getLayoutParams(width, width, margin, margin, 0, 0));
            mIvPic5.setLayoutParams(getLayoutParams(width, width, 0, margin, 0, 0));
            mIvPic6.setLayoutParams(getLayoutParams(width, width, margin, margin, 0, 0));
        }


        /**
         * 重设图片大小
         */
        public void initPicSize() {
            switch (witnessCard.affimages.size()) {
                case 1:
                    has1Pic();
                    break;
                case 2:
                    has2Pic();
                    break;
                case 3:
                    has3Pic();
                    break;
                case 4:
                    has4Pic();
                    break;
                case 5:
                    has5Pic();
                    break;
                case 6:
                    has6Pic();
                    break;
                default:
                    break;
            }


        }

        public void initVideoStub(WitnessCard card) {

            picStub = (ViewStub) view.findViewById(R.id.vs_witness_video);
            picStub.inflate();
            videoSurface = (SurfaceView) view.findViewById(R.id.video_surface);
            playUitls = new VideoPlayerUtils(videoSurface);
            playUitls.setonPlayCompletionListener(new VideoPlayerUtils.onPlayCompletionListener() {
                @Override
                public void PlayCompletion(PlayState playstate) {
                    switch (playstate) {
                        case START:
                            break;
                        case FINISH:
                            ivPlay.setVisibility(View.VISIBLE);
                            break;
                    }

                }
            });
            ivPlay = (ImageView) view.findViewById(R.id.iv_bofang);


        }


        public void initPicStub(WitnessCard card) {
            int size = card.affimages.size();
            switch (size) {
                case 1:
                    picStub = (ViewStub) view.findViewById(R.id.vs_witness_pic1);
                    break;
                case 2:
                    picStub = (ViewStub) view.findViewById(R.id.vs_witness_pic2);
                    break;
                case 3:
                    picStub = (ViewStub) view.findViewById(R.id.vs_witness_pic3);
                    break;
                case 4:
                    picStub = (ViewStub) view.findViewById(R.id.vs_witness_pic4);
                    break;
                case 5:
                    picStub = (ViewStub) view.findViewById(R.id.vs_witness_pic5);
                    break;
                case 6:
                    picStub = (ViewStub) view.findViewById(R.id.vs_witness_pic6);
                    break;
                default:
                    break;
            }
            picStub.inflate();
            mIvPic1 = (NetworkImageView) view.findViewById(R.id.iv_witness_pic1);
            mIvPic2 = (NetworkImageView) view.findViewById(R.id.iv_witness_pic2);
            mIvPic3 = (NetworkImageView) view.findViewById(R.id.iv_witness_pic3);
            mIvPic4 = (NetworkImageView) view.findViewById(R.id.iv_witness_pic4);
            mIvPic5 = (NetworkImageView) view.findViewById(R.id.iv_witness_pic5);
            mIvPic6 = (NetworkImageView) view.findViewById(R.id.iv_witness_pic6);


        }

        public void setWitnessState(Boolean hasWitness, int result) {
            witnessCard.witnessAttach.haswitness = hasWitness;
            witnessCard.witnessAttach.witresult = result;
            if (hasWitness) {
                mWitnessYes.setEnabled(false);
                mWitnessNo.setEnabled(false);
            } else {
                mWitnessYes.setEnabled(true);
                mWitnessNo.setEnabled(true);
            }

        }

        /**
         * 监听
         *
         * @param view
         */
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.tv_witness_yes:
                    setWitnessState(true, ParamConst.WITNESS_YES);
                    cardListener.onWitnessYes(witnessCard);
                    break;
                case R.id.tv_witness_no:
                    setWitnessState(true, ParamConst.WITNESS_NO);
                    cardListener.onWitnessNo(witnessCard);
                    break;
                case R.id.tv_witness_comments:
                    cardListener.onWitnessComments(witnessCard);
                    break;
                case R.id.iv_witness_pic1:
                    ImageDisplay.toDisplay(mActivity, imageList, 0);
                    break;
                case R.id.iv_witness_pic2:
                    ImageDisplay.toDisplay(mActivity, imageList, 1);
                    break;
                case R.id.iv_witness_pic3:
                    ImageDisplay.toDisplay(mActivity, imageList, 2);
                    break;
                case R.id.iv_witness_pic4:
                    ImageDisplay.toDisplay(mActivity, imageList, 3);
                    break;
                case R.id.iv_witness_pic5:
                    ImageDisplay.toDisplay(mActivity, imageList, 4);
                    break;
                case R.id.iv_witness_pic6:
                    ImageDisplay.toDisplay(mActivity, imageList, 5);
                    break;
                default:
                    break;
            }

        }
    }

    public interface WitnessCardListener {

        public void onWitnessNo(WitnessCard card);

        public void onWitnessComments(WitnessCard card);

        public void onWitnessYes(WitnessCard card);


    }
}
